package tech.senri.iot.socket.service

import com.fasterxml.jackson.databind.ObjectMapper
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import tech.senri.iot.socket.service.socket.SessionManager
import java.util.concurrent.CountDownLatch


@Service
class MessageHandleService(private val latch: CountDownLatch)
{
    private val logger = LoggerFactory.getLogger(this.javaClass)

    @Autowired
    private lateinit var objectMapper: ObjectMapper

    @Autowired
    private lateinit var requestMessageEncoder: RequestMessageEncoder

    fun handleMessage(message: String)
    {
        logger.info("收到返回消息：$message")
        latch.countDown()
    }

    fun handleRequestMessage(message: String)
    {
        logger.info("收到请求消息：$message")
        val node = objectMapper.readTree(message)
        val messageCode = node.path("messageCode").asInt()
        val funCode = node.path("funCode").asInt()
        requestMessageEncoder.encode(Pair(messageCode, funCode), message)?.let {
            SessionManager.sendMessage(it)
        }
        latch.countDown()
    }
}
